package glub.hlzds.mijia;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;



public class Utils {

    public static boolean logInfo = false;
    public static Map< String,String> cookies = new HashMap< String,String>();
    public static Map< String,String> retDatas = new HashMap< String,String>();

    public static JSONObject getV6(JSONObject arg3) {
        JSONObject v0 = new JSONObject();
        try {
            v0.put("params", arg3);
        }
        catch(Exception v3) {
            v3.printStackTrace();
        }
        return v0;
    }

    /**
     *  打印byte数组
     * @param res
     */
    public static void printBytes(byte[] res) {
        System.out.println(Arrays.toString(res));
    }

    private static String a2() {
        return t("94ac5cfb69e87bd7","");
    }
    public static String t2(String arg2, String arg3) {
        StringBuilder v1 = new StringBuilder();
        v1.append(arg2);
        v1.append(arg3);
        return new StringBuffer(v1.toString()).reverse().toString();
    }

    private static String t(String arg1, String arg2) {
        StringBuilder v0 = new StringBuilder();
        v0.append(arg1);
        v0.append(arg2);
        return t2(v0.toString(), "860f50db3569e448");
    }

    public static String codeSign(String arg2, JSONObject arg3, long arg4 ){
        String v0 = a2();
        StringBuilder v1 = new StringBuilder();
        v1.append(arg3.toString());
        v1.append(arg2);
        v1.append(v0);
        v1.append(arg4);
        return Encript.md5(v1.toString()).toUpperCase();
    }

    public static String codeSign(String arg2, JSONObject arg3, String arg4, long arg5) {
        String v0 = a2();
        StringBuilder v1 = new StringBuilder();
        v1.append(arg3.toString());
        v1.append(arg2);
        v1.append(v0);
        v1.append(arg5);
        v1.append(arg4);
        return Encript.md5(v1.toString()).toUpperCase();
    }


    /**
     * POST 璇锋眰
     * @param url
     * @param header
     * @param data
     * @return
     */
    public static String post(String url,Map<String,String> headers,Map<String,String> data) {
        Connection con = Jsoup.connect(url);
//		for(Entry<String,String> cookie:cookies.entrySet()){
//			con.cookie(cookie.getKey(),cookie.getValue());
//		}
        con.ignoreContentType(true);
        con.headers(headers) ;
        con.data(data);
        con.timeout(5000);
        con.method(Method.POST);

        Response response = null;
        try {
            response = con.execute();
            cookies=response.cookies();

            if(logInfo) {
                StringBuffer log = new StringBuffer();
                log.append("\n");
                log.append("\n");
                log.append("POST ");
                log.append(url);
                log.append("\n");
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    con.header(entry.getKey(), entry.getValue());
                    log.append(entry.getKey()+": "+entry.getValue());
                    log.append("\n");

                }
                log.append("\n");
                for (Map.Entry<String, String> entry : data.entrySet()) {
                    con.header(entry.getKey(), entry.getValue());
                    log.append(entry.getKey()+"="+entry.getValue());
                    log.append("&");
                }
                if(!data.isEmpty()) {
                    log.deleteCharAt(log.length() - 1);
                }

                log.substring(0,log.length()-1);
                log.append("\n");
                log.append("\n");
                log.append(response.body());
                log.append("\n");
                log.append("\n");
                System.out.println(log.toString());
            }else {
                System.out.println(response.body());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }



        return response.body();
    }

    public static Map<String,String> getXiomi(String url,Map<String,String> headers) {
        Map<String,String> map = new HashMap<String,String>();
        Connection con = Jsoup.connect(url);
//		for(Entry<String,String> cookie:cookies.entrySet()){
//			con.cookie(cookie.getKey(),cookie.getValue());
//		}

        con.ignoreContentType(true);
        con.timeout(5000);
        con.method(Method.GET);
        con.headers(headers) ;

        Response response = null;
        try {
            response = con.execute();
            map.put("extension-pragma", response.headers().get("extension-pragma"));
            map.put("body", response.body());
            cookies=response.cookies();
        } catch (IOException e) {
            e.printStackTrace();
            return map;
        }

        return map;
    }
    public static Map<String,String> postXiomi(String url,Map<String,String> headers,Map<String,String> data) {
        Map<String,String> map = new HashMap<String,String>();

        Connection con = Jsoup.connect(url);
//		for(Entry<String,String> cookie:cookies.entrySet()){
//			con.cookie(cookie.getKey(),cookie.getValue());
//		}
        con.ignoreContentType(true);
        con.headers(headers) ;
        con.data(data);
        con.timeout(5000);
        con.method(Method.POST);

        Response response = null;
        try {
            response = con.execute();
            map.put("extension-pragma", response.headers().get("extension-pragma"));
            map.put("body", response.body());
            cookies=response.cookies();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return map;
        }

        return map;
    }






    public static String get(String url) throws IOException {
        Connection con = Jsoup.connect(url);
//		for(Entry<String,String> cookie:cookies.entrySet()){
//			con.cookie(cookie.getKey(),cookie.getValue());
//		}

        con.ignoreContentType(true);
        con.timeout(30000);
        con.method(Method.GET);

        Response response = null;
        try {
            response = con.execute();
            cookies=response.cookies();
            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";

    }

    public static String get(String url,Map<String,String> headers) {
        Connection con = Jsoup.connect(url);
        con.ignoreContentType(true);
        con.timeout(5000);
        con.method(Method.GET);
        con.headers(headers) ;


        Response response = null;
        try {
            response = con.execute();
            cookies=response.cookies();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }

        if(logInfo) {
            StringBuffer log = new StringBuffer();
            log.append("\n");log.append("\n");
            log.append("POST ");
            log.append(url);
            log.append("\n");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                con.header(entry.getKey(), entry.getValue());
                log.append(entry.getKey()+": "+entry.getValue());
                log.append("\n");

            }
            log.append("\n");
            log.append(response.body());
            log.append("\n");
            log.append("\n");
            System.out.println(log.toString());
        }else {
            System.out.println(response.body());
        }

        return response.body();
    }

    /**
     * POST
     * @param url
     * @param header
     * @param data
     * @return
     */
    public static String post(String url,Map<String,String> headers,String data) {
        Connection con = Jsoup.connect(url);
//		for(Entry<String,String> cookie:cookies.entrySet()){
//			con.cookie(cookie.getKey(),cookie.getValue());
//		}
        con.ignoreContentType(true);
        con.requestBody(data);
        con.timeout(5000);
        con.method(Method.POST);
        con.headers(headers) ;


        Response response = null;
        try {
            response = con.execute();
            cookies=response.cookies();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }

        if(logInfo) {
            StringBuffer log = new StringBuffer();
            log.append("\n");log.append("\n");
            log.append("POST ");
            log.append(url);
            log.append("\n");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                con.header(entry.getKey(), entry.getValue());
                log.append(entry.getKey()+": "+entry.getValue());
                log.append("\n");

            }
            log.append("\n");
            log.append(data);
            log.append(response.body());
            log.append("\n");
            log.append("\n");
            System.out.println(log.toString());
        }else {
            System.out.println(response.body());
        }

        return response.body();
    }

    /**
     * 复制map对象
     * @explain 将paramsMap中的键值对全部拷贝到resultMap中；
     * paramsMap中的内容不会影响到resultMap(深拷贝)
     * @param paramsMap
     *     被拷贝对象
     * @param resultMap
     *     拷贝后的对象
     */
    public static void mapCopy(Map paramsMap, Map resultMap) {
        if (resultMap == null) resultMap = new HashMap();
        if (paramsMap == null) return;

        Iterator it = paramsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");
        }
    }


    /**
     *    拼接url
     * @param url
     * @param auth
     * @return
     */
    public static String urlSplicing(String url,String auth) {
        String st = "";
        try {
            st = "POST&"+URLEncoder.encode(url.toString(),"UTF-8")+"&";
        } catch (UnsupportedEncodingException e) {
            System.out.println("url 拼接失败");
            e.printStackTrace();
        }
        st += auth;
        return st;
    }


    /**
     * 获得 authorization
     * @param authorizationMap
     * @return
     */
    public static String getAuthorization(Map<String,String> authorizationMap) {
        if(authorizationMap==null || authorizationMap.isEmpty()) {
            try {
                throw new Exception("authorizationMap 为空");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String authorization = "OAuth ";

        for (Object key : authorizationMap.keySet()) {
            authorization += key + "=\"" + authorizationMap.get(key) + "\", ";
        }
        authorization = authorization.substring(0, authorization.length() - 1);


        return authorization;
    }

    /**
     * 是否节假日
     * @param date
     * @return
     */
    public static boolean isHoliday(String date) {
        boolean hd = false; //不是节假日

        String res;
        try {
            res = Utils.get("http://api.goseek.cn/Tools/holiday?date="+date);
        } catch (IOException e) {
            try {
                System.out.println("获取");
                res = Utils.get("http://api.goseek.cn/Tools/holiday?date="+date);
            } catch (IOException e1) {
                return hd;
            }
            e.printStackTrace();
        }
        JSONObject dataJson = JSONObject.parseObject(res);
        String code = dataJson.getString("code")+"";
        String data = dataJson.getString("data")+"";

        if("10000".equals(code)) {
            if(!"0".equals(data)) {
                hd = true;
            }
        }else {
            System.out.println("获取假期失败");
        }
        return hd;
    }

    /**
     * 获取当前时间
     * @return
     */
    public static String getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        return formatter.format(currentTime);
    }
    /**
     * 获取当前时间
     * @return
     */
    public static String getNowDate(String format) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(currentTime);
    }

    /**
     * 格式化时间
     * @return
     */
    public static String formatDate(Date date,String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date);
    }

    /**
     * 将map的值用&拼接
     * @param map
     */
    public static String mapSplicing(Map<String,String> map) {
        if(map==null || map.isEmpty()) {
            System.out.println("map is null or is empty");
            return "";
        }
        String str = "";

        for (Map.Entry<String, String> entry : map.entrySet()) {
            try {
                str += URLEncoder.encode(entry.toString() +"&","utf-8") ;
            } catch (UnsupportedEncodingException e) {
                System.out.println("拼接数据失败");
                e.printStackTrace();
            }
        }
        str = str.substring(0, str.length()-3);
        return str;
    }

    /**
     * 将map 升序排序
     * @param map
     * @return
     */
    public static TreeMap<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            System.out.println("排序失败，map 为空 或者 null");
            return null;
        }

        TreeMap<String, String> sortMap = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String o1, String o2) {
                        return o1.compareTo(o2);
                    }});
        sortMap.putAll(map);

        return sortMap;
    }

    /**
     * 打印map中的值
     * @param map
     */

    public static void printMap(Map<String,String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() +"="+entry.getValue());
        }
    }

    /**
     *  将map 里所有的value 进行url编码
     * @param data
     */
    public static void dataToUrlCode(Map<String,String> data) {

        for (Map.Entry<String, String> entry : data.entrySet()) {
            try {
                String value = entry.getValue()!=null?entry.getValue():"";
                data.put(entry.getKey(),URLEncoder.encode(value,"utf-8"));
            } catch (UnsupportedEncodingException e) {
                System.out.println("data to URLEncoder error");
                e.printStackTrace();
            }
        }

    }

}
